#include "Hardware/Timer.h"
#include "Hardware/Interrupt.h"
#include <intrins.h>

bool OverTimeFlag;

void Timer0Init(uint8 workMode,uint8 high,uint8 low)
{
	switch(workMode)
	{
	case 0:
	{
		TMOD |= 0x1;
	}break;
	case 1:
	{
		TMOD |= 0x2;
	}break;
	default:
		return;
	}
	
	TH0=high;
	TL0=low;
	TF0=0;
	TR0=1;
}

void Timer1Init(uint8 workMode,uint8 high,uint8 low)
{
	switch(workMode)
	{
	case 0:
	{
		TMOD |= 0x10;
	}break;
	case 1:
	{
		TMOD |= 0x20;
	}break;
	default:
		return;
	}
	
	TH1=high;
	TL1=low;
	TF1=0;
	TR1=1;
}

void ClearTimer0()
{
	TR0=0;
}

void ClearTimer1()
{
	TR1=0;
}

void Delay(uint16 ms)
{
	while(ms--)
	{
		Timer0Init(0,0xfc,0x66); //设置定时器0 延时1ms
		while(!TF0)
		{
			_nop_();
		}
		Timer0Init(0,0xfc,0x66);
	}
	ClearTimer0();
}

void Delay5us()
{
#if XTAL==11059200UL
	_nop_();
	_nop_();
	_nop_();
	_nop_();
	_nop_();
#elif XTAL==12000000UL
	_nop_();
	_nop_();
	_nop_();
	_nop_();
	_nop_();
#elif XTAL==22118400UL
	_nop_();
	_nop_();
	_nop_();
	
	_nop_();
	_nop_();
	_nop_();
	
	_nop_();
	_nop_();
	_nop_();
	
	_nop_();
	_nop_();
	_nop_();
	
	_nop_();
	_nop_();
	_nop_();
#endif
}

void Delay30us()
{
	Timer0Init(0,0xff,0xe4);
	while(!TF0);
	ClearTimer0();
}

void Delay60us()
{
	Timer0Init(0,0xff,0xc9);
	while(!TF0);
	ClearTimer0();
}

void Delay550us()
{
	Timer0Init(0,0xfe,0x05);
	while(!TF0);
	ClearTimer0();
}

void StartCountTime()
{
	OverTimeFlag=false;
	Timer0Init(0,0,0);
	OpenINT();
	OpenCounter0INT();
}

bool EndCountTime(uint8 *_TH0,uint8 *_TL0)
{
	ClearTimer0();
	CloseCounter0INT();
	CloseINT();
	*_TH0=TH0;
	*_TL0=TL0;
	return !OverTimeFlag;
}

Counter0_Interrupt(IsOverTime)
{
	OverTimeFlag=true;
}